<template>
  <div class="login-box">
    <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="80px"
             class="demo-ruleForm">
      <h2>后台管理系统</h2>
      <el-form-item label="账号：" prop="username">
        <el-input v-model="ruleForm.username" autocomplete="off"/>
      </el-form-item>

      <el-form-item label="密码：" prop="password">
        <el-input v-model="ruleForm.password" type="password" autocomplete="off"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" class="loginBtn" @click="submitForm(ruleFormRef)">登录</el-button>
        <el-button class="loginBtn" @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script lang="ts">
import {defineComponent, reactive, toRefs, ref} from 'vue'
import {useRouter} from 'vue-router'
import {loginData} from '@/class/login'
import {LoginView} from '@/request/api'

import type {FormInstance} from 'element-plus'


export default defineComponent({
  setup() {

    const ruleFormRef = ref<FormInstance>()

    const data = reactive(new loginData())

    const rules = {
      username: [
        {required: true, message: '请输入你的账号', trigger: 'blur'},
        {min: 3, max: 10, message: '账号的长度在3到10之间', trigger: 'blur'},
      ],
      password: [
        {required: true, message: '请输入你的密码', trigger: 'blur'},
        {min: 3, max: 10, message: '密码的长度在3到10之间', trigger: 'blur'},
      ]
    }

    const router = useRouter()

    const submitForm = (formElement: FormInstance | undefined) => {
      if (!formElement) return
      //对表单的内容进行一个验证
      formElement.validate((valid) => {
        if (valid) {
          new LoginView().login(data.ruleForm).then(res => {
            //保存token
            localStorage.setItem("token", res.data.token)
            // 跳转页面到首页
            router.push("/home")
          })
        } else {
          console.log('error submit!')
          return false
        }
      })
    }

    const resetForm = (formElement: FormInstance | undefined) => {
      if (!formElement) return
      formElement.resetFields()
      data.ruleForm.username = ""
      data.ruleForm.password = ""
    }


    return {
      ...toRefs(data),
      ruleFormRef,
      rules,
      submitForm,
      resetForm,
    }
  }
})
</script>

<style lang="scss" scoped>
.login-box {
  width: 100%;
  height: 100%;
  // background: url("../assets/bg.jpg");
  background: #585D5F;
  padding: 0.1px;
  text-align: center;

  .demo-ruleForm {
    width: 500px;
    margin: 200px auto;
    background-color: #fff;
    padding: 40px;
    border-radius: 20px;
  }

  .loginBtn {
    width: 48%;
  }

  h2 {
    margin-bottom: 15px;
  }
}
</style>
